import { login, loginOut, getInfo } from '@/api/user'
import { getStorage, setStorage, removeStorage } from '@/utils/storage'
// import { resetRouter } from '@/router'

const state = {
    token: getStorage('token'),
    name: '',
    avatar: '',
    roles: [],
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles
    }
}

const actions = {
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(result => {
                const { data: res } = result
                commit('SET_TOKEN', res.data.token)
                setStorage('token', res.data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(result => {
                const { data: res } = result
                const { name, avatar, roles } = res.data
                commit('SET_NAME', name)
                commit('SET_AVATAR', avatar)
                commit('SET_ROLES', roles)
                resolve(res.data)
            }).catch(error => {
                reject(error)
            })
        })
    },

    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            loginOut().then(() => {
                removeStorage('token')
                commit('SET_NAME', '')
                commit('SET_AVATAR', '')
                commit('SET_ROLES', [])
                // resetRouter()
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    removeToken({ commit }) {
        return new Promise(resolve => {
            removeStorage('token')
            commit('SET_TOKEN', '')
            commit('SET_NAME', '')
            commit('SET_AVATAR', '')
            commit('SET_ROLES', [])
            resolve()
        })
    },
}

export default {
    state,
    mutations,
    actions
}